from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import user_login_data, db
from info.models import News, Category
from info.modules.profile import profile_bp
from info.utits.pic_storage import pic_storage
from info.utits.response_code import RET


@profile_bp.route('/my_followed',methods=["GET","POST"])
@user_login_data
def my_followed():
    return "123"


@profile_bp.route('/news_list',methods=["GET","POST"])
@user_login_data
def news_list():
    """获取用户发布的新闻列表数据"""
    p = request.args.get("p",1)
    user = g.user
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数内容格式错误")

    news_list = []
    current_page = 1
    total_page = 1
    news_dict_list = []

    if user:
        try:
            paginate = News.query.filter(News.user_id==user.id).paginate(p,constants.USER_NEWS_PAGE_MAX_COUNT,False)
            news_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="查询用户发布新闻分页数据异常")
        for news in news_list if news_list else []:
            news_dict_list.append(news.to_review_dict())
    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("profile/user_news_list.html",data=data)


@profile_bp.route('/news_release',methods=['GET','POST'])
@user_login_data
def news_release():
    """新闻发布"""
    if request.method=="GET":
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="查询分类数据异常")
        category_dict_list = []
        for category in categories if categories else []:
            category_dict_list.append(category.to_dict())

        category_dict_list.pop(0)

        data = {
            "categories":category_dict_list
        }
        return render_template("profile/user_news_release.html",data=data)

    # 获取参数,   标题   分类号  摘要  图片索引   内容
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    user = g.user

    source = "个人发布"

    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")
    try:
        index_image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="读取图片异常")

    try:
        pic_name = pic_storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传到七牛云失败")

    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX+pic_name
    news.source = source
    news.content = content

    news.status = 1
    news.user_id = user.id

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存新闻数据异常")

    return jsonify(errno=RET.OK,errmsg="发布新闻成功")


@profile_bp.route('/collection',methods=["GET","POST"])
@user_login_data
def user_collection_news():
    p = request.args.get("p",1)
    user = g.user

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数内容格式错误")

    collections = []
    current_page = 1
    total_page = 1
    collection_dict_list = []
    if user:
        try:
            paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
            collections = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="查询用户收藏分页数据异常")

        for news in collections if collections else []:
            collection_dict_list.append(news.to_basic_dict())

    data =  {
        "collections":collection_dict_list,
        "current_page":current_page,
        "total_page": total_page
    }
    return render_template("profile/user_collection.html",data=data)


@profile_bp.route('/pass_info',methods=["GET","POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        return render_template("profile/user_pass_info.html")

    old_password = request.json.get("old_password")
    news_password = request.json.get("new_password")

    if not all([old_password,news_password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    if not user.check_password(old_password):
        return jsonify(errno=RET.DATAERR,errmsg="旧密码填写错误")
    user.password = news_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="修改密码异常")

    return jsonify(RET.OK,errmsh="修改密码成功")


@profile_bp.route('/pic_info',methods=["GET","POST"])
@user_login_data
def pic_info():
    """设置用户头像"""
    user = g.user
    if request.method == "GET":
        return render_template("profile/user_pic_info.html")

    try:
        pic_data = request.files.get("avatar").read()
    except Exception as e:
        current_app.loger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="读取图片数据异常")

    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    try:
        pic_name = pic_storage(pic_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传图片到七牛云异常")

    user.avatar_url = pic_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存用户头像数据异常")

    full_url = constants.QINIU_DOMIN_PREFIX+pic_name

    data = {
        "avatar_url": full_url
    }
    print(full_url)
    return jsonify(errno=RET.OK,errmsg="修改用户头像成功",data=data)


@profile_bp.route('/base_info',methods=["GET","POST"])
@user_login_data
def user_base_info():
    """展示用户基本资料"""
    print("user_base_info")
    user = g.user
    if request.method == "GET":
        data = {
            "user_info":user.to_dict() if user else None
        }
        return render_template("profile/user_base_info.html",data=data)

    param_dict = request.json
    signature = param_dict.get("signature")
    nick_name = param_dict.get("nick_name")
    gender = param_dict.get("gender")

    if not all([signature,nick_name,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")

    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    if gender not in ["MAN","WOMAN"]:
        return jsonify(errno=RET.PARAMERR,errmsg="action参数错误")

    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    session["nick_name"] = nick_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存数据异常")
    return jsonify(errno=RET.OK,errmsg="保存用户基本资料成功")


@profile_bp.route('/info',methods=["POST","GET"])
@user_login_data
def get_user_info():
    """展示用户个人中心数据"""
    print('1111')
    user =g.user
    data = {
        "user_info":user.to_dict() if user else None
    }
    return render_template("profile/user.html",data=data)
